package com.tyq.auth.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tyq.auth.common.ResultData;
import com.tyq.auth.common.ReturnCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义无权限请求处理器
 *
 * @author 谭永强
 * @date 2024-05-20
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 处理拒绝访问的异常
     *
     * @param request               请求
     * @param response              响应
     * @param accessDeniedException 拒绝访问的异常
     * @throws IOException      IO异常
     * @throws ServletException Servlet异常
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ResultData<Authentication> resultData = new ResultData<>();
        resultData.setCode(ReturnCode.RC403.getCode());
        resultData.setMessage("无访问权限!");
        objectMapper.writeValue(response.getWriter(), resultData);
    }
}
